﻿using Dtmcli;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using MQCommon;
using MQCommon.SagaModel;
using MySqlConnector;
using SagaUser.Model;


// For more information on enabling Web API for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860

namespace SagaUser.Controllers
{
    [Route("/api")]
    [ApiController]
    public class TccUserController : ControllerBase
    {
        private readonly IBranchBarrierFactory _barrierFactory;

        public TccUserController(IBranchBarrierFactory barrierFactory)
        {
            _barrierFactory = barrierFactory;
        }
        [HttpPost("TccUserTry")]
        public async Task<IActionResult> TccUserTry([FromQuery] string gid, [FromQuery] string trans_type,
            [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {


            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            var obj = TransResponse.BuildSucceedResponse();
            using (MySqlConnection conn = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(conn, async (tx) =>
                {
                    var UserMoneys = dh.Query<UserMoney>($"select *  from User_Money where id={body.UserId} and balance=0");
                    if (UserMoneys.Count > 0)
                    {
                        dh.Execute($"update User_Money set  balance=1,trading_balance=1 where id={body.UserId}");

                    }
                    else
                    {
                        obj = TransResponse.BuildFailureResponse();
                    }
                    await Task.CompletedTask;
                });
            }

            return Ok(obj);
        }

        [HttpPost("TccUserConfirm")]
        public async Task<IActionResult> TccUserConfirm([FromQuery] string gid, [FromQuery] string trans_type,
           [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {

            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);
            DapperHelper dh = new DapperHelper();
            var obj = TransResponse.BuildFailureResponse();
            using (MySqlConnection conn = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(conn, async (tx) =>
                {
                    var UserMoneys = dh.Query<UserMoney>($"select *  from User_Money where id={body.UserId}");
                    var money = UserMoneys[0].money + body.Money;

                    dh.Execute($"insert into User_Accounts values(null,{body.BusinessID},{body.UserId},{body.Money},'koukuan',{UserMoneys[0].money},'{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}')");
                    dh.Execute($"update User_Money set money={money},updatetime='{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}',balance=0,trading_balance=0 where id={body.UserId}");
                    obj = TransResponse.BuildSucceedResponse();
                    await Task.CompletedTask;
                });
            }

            return Ok(obj);
        }
        [HttpPost("TccUserCancel")]
        public async Task<IActionResult> TccUserCancel([FromQuery] string gid, [FromQuery] string trans_type,
           [FromQuery] string branch_id, [FromQuery] string op, [FromBody] OrderModel body)
        {

            var branchBarrier = _barrierFactory.CreateBranchBarrier(Request.Query);

            DapperHelper dh = new DapperHelper();
            var obj = TransResponse.BuildFailureResponse();
            using (MySqlConnection conn = new MySqlConnection(dh.connectstr()))
            {
                await branchBarrier.Call(conn, async (tx) =>
                {
                    //这里操作回滚并解锁
                    var UserMoneys = dh.Query<UserMoney>($"select *  from User_Money where id={body.UserId}");
                    var money = UserMoneys[0].money - body.Money;
                    dh.Execute($"insert into User_Accounts values(null,{body.BusinessID},{body.UserId},{body.Money},'huigun',{UserMoneys[0].money},'{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}')");
                    dh.Execute($"update User_Money set money={money},updatetime='{DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss")}',balance=0,trading_balance=0 where id={body.UserId}");
                    await Task.CompletedTask;
                });
            }

            return Ok(TransResponse.BuildSucceedResponse());
        }
    }
}
